package com.isoftstone.project.system.controller;

import com.isoftstone.common.BusinessException;
import com.isoftstone.common.constant.Constants;
import com.isoftstone.framework.aop.OpLogAopController;
import com.isoftstone.framework.controller.BaseController;
import com.isoftstone.framework.domain.Page;
import com.isoftstone.framework.domain.PageData;
import com.isoftstone.framework.domain.Tidings;
import com.isoftstone.project.system.domain.SysRole;
import com.isoftstone.project.system.service.ISysRoleService;
import com.isoftstone.project.system.service.ISysUserRoleService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Controller
public class SysRoleController extends BaseController {

    @Autowired
    ISysRoleService sysRoleService;
    @Autowired
    ISysUserRoleService sysUserRoleService;

    @RequestMapping("/system/role/rolelist")
    public ModelAndView rolelist() {
        return new ModelAndView("system/role/role_list");
    }

    @RequestMapping("/system/role/getRolelistPage")
    @ResponseBody
    public Object getRolelistPage(Page page) {
        Tidings<List<SysRole>> tidings = new Tidings<List<SysRole>>();
        PageData pd = this.getPageData();
        page.setPd(pd);
        try {
            List<SysRole> roleList = sysRoleService.getRolelistPage(page);
            tidings.setT(roleList);
            tidings.setTotalResult(page.getTotalResult());
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(Constants.ERRORMSG);
        }
        return tidings;
    }


    @RequestMapping("system/role/saveUpdateRole")
    @ResponseBody
    @OpLogAopController(module="角色管理",methods="updateRole",description="0")
    public Object updateRole(@ModelAttribute("role")SysRole role) {
        Tidings<String> tidings = new Tidings<String>();
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            if(StringUtils.isBlank(role.getRoleId())){
                request.setAttribute("description","添加角色");
                SysRole sysRole = sysRoleService.getRoleByCode(role.getRoleCode());
                if(sysRole == null){
                    SysRole sysRole1 = sysRoleService.getRoleByCodeName(role.getRoleName());
                    if(sysRole1 == null){
                        role.setRoleId(this.get32UUID());
                        role.setCreateUser(this.getUser().getUserId());
                        role.setCreateDate(new Date());
                        sysRoleService.saveRole(role);
                        tidings.setStatus(Constants.SUCCESS);
                        tidings.setMsg("保存成功！");
                    }else{
                        tidings.setStatus(Constants.ERROR);
                        tidings.setMsg("角色名称重复！");
                    }
                }else{
                    tidings.setStatus(Constants.ERROR);
                    tidings.setMsg("编码重复！");
                }
            }else{
                request.setAttribute("description","修改角色");

                sysRoleService.updateRole(role);
                tidings.setStatus(Constants.SUCCESS);
                tidings.setMsg("修改成功！");

            }
        } catch (Exception e) {
            tidings.setStatus(Constants.ERROR);
            tidings.setMsg("保存失败！");
            e.printStackTrace();
        }

        return tidings;
    }

    @RequestMapping("/system/role/deleteRole")
    @ResponseBody
    @OpLogAopController(module="角色管理",methods="deleteSysRole",description="删除角色")
    public Object deleteSysRole(String roleId,String roleCode) {
        Tidings<String> tidings = new Tidings<String>();
        try {
            //超级管理员角色和高级用户角色无法删除
            if("admin".equals(roleCode) ) {
                tidings.setStatus(Constants.ERROR);
                tidings.setMsg("此角色不能被删除！");
            }else {
                //判断是否有用户使用这个角色
                List<String> list = sysUserRoleService.getRolesByroleId(roleId);
                if (list == null || list.size() == 0) {
                    sysRoleService.deleteRole(roleId);
                    sysUserRoleService.deleteByroleId(roleId);
                    tidings.setStatus(Constants.SUCCESS);
                    tidings.setMsg("删除成功！");
                } else {
                    tidings.setStatus(Constants.ERROR);
                    tidings.setMsg("有用户使用本角色,无法删除！");
                }
            }
        } catch (Exception e) {
            tidings.setStatus(Constants.ERROR);
            tidings.setMsg("删除失败！");
            e.printStackTrace();
        }
        return tidings;
    }

    @RequestMapping("/system/role/getRoleById")
    public ModelAndView getRoleById(String roleId) {
        ModelAndView md = new ModelAndView();
        try {
            SysRole sysRole = sysRoleService.getRoleById(roleId);
            md.addObject("sysRole", sysRole);
        } catch (Exception e) {
            e.printStackTrace();
        }
        md.setViewName("system/role/role_details");
        return md;
    }

    @RequestMapping("/system/role/toRoleEdit")
    public ModelAndView toRoleEdit(String roleId) {
        ModelAndView md = new ModelAndView();
        try {
            SysRole sysRole = sysRoleService.getRoleById(roleId);
            md.addObject("sysRole", sysRole);
        } catch (Exception e) {
            e.printStackTrace();
        }
        md.setViewName("system/role/role_edit");
        return md;
    }

    //查询SysRole信息(用户授权)
    @RequestMapping("/system/user/toUserLimit")
    public ModelAndView getLimitToUser(String userId) {
        ModelAndView md = new ModelAndView();
        try {
            List<String>list = sysUserRoleService.getRolesByUserId(userId);

            List<SysRole> sysRole = sysRoleService.getRole(this.getUser().getUserId().equals(Constants.ADMIN)?null:this.getUser().getUserId());
            for (String role : list) {
                for (SysRole sysRole1 : sysRole) {
                    if(role.equals(sysRole1.getRoleCode())){
                        sysRole1.setChecked("checked");
                    }
                }
            }
            md.addObject("sysRole", sysRole);
            md.addObject("userId", userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        md.setViewName("system/user/user_limit");
        return md;
    }
    //保存选择过角色权限的用户
    @RequestMapping("/system/user/saveUserLimit")
    @ResponseBody
    @OpLogAopController(module="用户信息",methods="saveUserLimit",description="用户授权")
    public Object saveUserLimit() {
        Tidings<String> tidings = new Tidings<String>();
        PageData pd = this.getPageData();
        try {
            String userId = pd.getString("userId");
            String roleId = pd.getString("roleId");

            if (StringUtils.isBlank(roleId)) {
                sysUserRoleService.deleteByUserId(userId);
            } else {
                sysUserRoleService.deleteByUserId(userId);
                String[] split = roleId.split(",");
                for (String s : split) {
                    sysUserRoleService.saveUserRole(userId, s);
                }
            }
            tidings.setStatus(Constants.SUCCESS);
            tidings.setMsg("保存成功！");

        } catch (Exception e) {
            tidings.setStatus(Constants.ERROR);
            tidings.setMsg("保存失败！");
            e.printStackTrace();
        }
        return tidings;
    }



}

